from typing import List

from flask import current_app

from src import db
from src.model.example.member import Member
from src.service.base_service import BaseService
from src.struct.dto.member_dto import MemberDTO
from src.struct.req.example.member_create_req import MemberCreateReq
from src.struct.req.example.member_update_req import MemberUpdateReq


class MemberService(BaseService):

    def all(self) -> List[MemberDTO]:
        """获取全部员工"""
        members = Member.query.all()
        return [MemberDTO.from_model(member) for member in members]

    def create(self, member_create_req: MemberCreateReq) -> Member:
        """创建用户"""
        member = Member(
            name=member_create_req.name,
            email=member_create_req.email
        )
        try:
            db.session.add(member)
            db.session.commit()
            return member
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"创建用户失败: {str(e)}")
            raise Exception("创建用户失败")

    def update(self, member_update_req: MemberUpdateReq) -> Member:
        """编辑用户"""
        member = Member.query.get_or_404(member_update_req.id)
        try:
            member.name = member_update_req.name
            member.email = member_update_req.email
            db.session.commit()
            return member
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"更新用户失败: {str(e)}")
            raise Exception("更新用户失败")

    def delete(self, member_id: int) -> bool:
        """删除用户"""
        member = Member.query.get_or_404(member_id)
        try:
            db.session.delete(member)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"删除用户失败: {str(e)}")
            raise Exception("删除用户失败")
